const Koa = require("koa")
const KoStaticCache = require("koa-static-cache")
const koaRouter = require("koa-router")
const koaBody = require("koa-body")
const fs = require("fs")

const app = new Koa()
const router = new koaRouter()

app.use(KoStaticCache({
  prefix: "/",
  dir: "./public"
}))
app.use(koaBody({
  multipart: true,
  formidable: {
    uploadDir: "./public/files",
    keepExtensions: true
  }

}))

router.get("/getData", async (ctx, next) => {

  return new Promise((resolve, reject) => {
    setTimeout(() => {
      ctx.body = "hello ajax!"
      resolve()
    }, 3000)
  })

})

// 下载
router.get("/download", async (ctx, next) => {
  // stream 流
  const data = fs.readFileSync("./public/files/1.pptx")
  ctx.body = data
})

router.post("/upload", async (ctx, next) => {
  console.log(ctx.request.files)
  console.log(ctx.request.body)
  ctx.body = "上传成功"
})

app.use(router.routes())

app.listen(8080, () => {
  console.log("run on http://localhost:8080")
})
